using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Xml.Linq;
using System.Xml.XPath;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Security;

namespace LifeInSharePoint.Blog.Features.SITE.LISP.Blog.ControlAdapter
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("ead14450-f3d5-4bf7-8179-e214d1a3e778")]
    public class SITELISPBlogEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.
        private const string WEBPART_ADAPTER_CONTROL_TYPE = "System.Web.UI.WebControls.WebParts.WebPartZone";
        private const string WEBPART_ADAPTER_TYPE = "LifeInSharePoint.Blog.Common.WebPartAdapter.WebPartRenderControlAdapter, LifeInSharePoint.Blog, Version=1.0.0.0, Culture=neutral, PublicKeyToken=510c80fac59f370f";

        private void LogException(string message, Exception e)
        {
            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("LifeInSharePoint Blog", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, "{0}: {1}\r\n{2}\r\n{3}", new object[] { message, e.Message, e.StackTrace, e.StackTrace, e.ToString() });
        }

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {

            // Get the site collection
            SPSite SiteCollection = (SPSite)properties.Feature.Parent;

            // Load up the Compat.browser and add the the control adaptor
            try
            {
                UpdateCompatBrowser(SiteCollection);
            }
            catch (Exception e)
            {
                LogException(
                    "Exception in Portal Feature Activated occurredError. Error updating compat browser",
                    e);
            }
        }

        /// <summary>
        /// Add our control adaptor to the Compat.Browser file
        /// </summary>
        /// <param name="SiteCollection"></param>
        private void UpdateCompatBrowser(SPSite SiteCollection)
        {

            // Loop through each webapplication and try and add the control adaptor

            foreach (var IISSetting in SiteCollection.WebApplication.IisSettings)
            {
                String pathToCompatBrowser = IISSetting.Value.Path + @"\App_Browsers\compat.browser";
                XElement compatBrowser = XElement.Load(pathToCompatBrowser);

                // Check we don't already have it


                XElement existingElement = compatBrowser.XPathSelectElement(String.Format(
                                "./browser[@refID = \"default\"]/controlAdapters/adapter[@controlType=\"{0}\" and @adapterType=\"{1}\"]",
                                WEBPART_ADAPTER_CONTROL_TYPE,
                                WEBPART_ADAPTER_TYPE));

                if (existingElement == null)
                {
                    // We don't already have it - add it and save

                    // Get the node for the default browser.
                    XElement controlAdapters = compatBrowser.XPathSelectElement("./browser[@refID = \"default\"]/controlAdapters");

                    // Create and add the markup
                    XElement newAdapter = new XElement("adapter");
                    newAdapter.SetAttributeValue("controlType", WEBPART_ADAPTER_CONTROL_TYPE);
                    newAdapter.SetAttributeValue("adapterType", WEBPART_ADAPTER_TYPE);

                    controlAdapters.Add(newAdapter);

                    // Overwrite the old version of compat.browser with the new version
                    compatBrowser.Save(pathToCompatBrowser);



                }


            }


        }
        // Uncomment the method below to handle the event raised after a feature has been activated.

        //public override void FeatureActivated(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is deactivated.

        //public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
